package cn.xiongxf.web.controller;

import cn.xiongxf.domain.Login;
import cn.xiongxf.query.LoginQuery;
import cn.xiongxf.result.JsonResult;
import cn.xiongxf.result.PageList;
import cn.xiongxf.service.ILoginService;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    public ILoginService loginService;

    //登录成功后重定向地址
    @RequestMapping("/loginSuccess")
    public String loginSuccess() {
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        return "登录成功";
    }


    /**
     * 带条件分页查询数据
     */
    @RequestMapping(value = "/pagelist", method = RequestMethod.POST)
    public JsonResult page(@RequestBody LoginQuery query) {
        Page<Login> page = new Page<Login>(query.getPage(), query.getRows());
        page = loginService.selectPage(page);
        return JsonResult.success(new PageList<Login>(page.getTotal(), page.getRecords()));
    }

    /**
     * 查询所有对象
     */
    // 方法授权(更灵活，目标更明确)：用有该权限才能访问
    @PreAuthorize("hasAuthority('login:list')")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public JsonResult list() {
        return JsonResult.success(loginService.selectList(null));
    }

    /**
     * 查询单个对象
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public JsonResult get(@PathVariable("id") Long id) {
        return JsonResult.success(loginService.selectById(id));
    }

    /**
     * 删除对象
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public JsonResult delete(@PathVariable("id") Long id) {
        loginService.deleteById(id);
        return JsonResult.success();
    }

//    /**
//    * 保存/修改对象
//    */
//    @RequestMapping(value="/save",method= RequestMethod.POST)
//    public JsonResult saveOrUpdate(@RequestBody Login login){
//        if(login.getId()!=null){
//            loginService.updateById(login);
//        }else{
//            loginService.insert(login);
//        }
//        return JsonResult.success();
//    }

    /**
     * 保存对象
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public JsonResult save(@RequestBody Login login) {
        loginService.insert(login);
        return JsonResult.success(login.getId());
    }

}
